package org.haifi.webapp.action;

import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.google.common.collect.Lists;

/**
 * 动态调整log4j的日志级别
 * 
 * @author joycube2
 * 
 */
public class Log4jAction extends BasicAction {
	private static List<String[]> loggers = null;
	private static List<String> logLevels = null;

	private String loggerPackage;
	private String loggerLevel;

	public String getLoggerLevel() {
		return loggerLevel;
	}

	public void setLoggerLevel(String loggerLevel) {
		this.loggerLevel = loggerLevel;
	}

	public String getLoggerPackage() {
		return loggerPackage;
	}

	public void setLoggerPackage(String loggerPackage) {
		this.loggerPackage = loggerPackage;
	}

	public List<String[]> getLoggers() {
		return loggers;
	}

	public List<String> getLogLevels() {
		return logLevels;
	}

	@SuppressWarnings("unchecked")
	public String list() {
		if (!StringUtils.isEmpty(loggerPackage)
				&& !StringUtils.isEmpty(loggerLevel)) {
			Logger logger = Logger.getLogger(loggerPackage);
			logger.setLevel(Level.toLevel(loggerLevel));

			// 设置loggers为空，重新去取logger级别
			loggers = null;
		}

		if (loggers == null) {
			// 没必要同步，后台管理员页面，不会有多用户并发的情况
			loggers = Lists.newArrayList();
			Enumeration<Logger> logManager = LogManager.getCurrentLoggers();
			while (logManager.hasMoreElements()) {
				Logger logger = (Logger) logManager.nextElement();

				if (logger.getLevel() == null) {
					continue;
				}

				String name = logger.getName();
				String level = logger.getLevel().toString();

				if (name.startsWith("org.haifi") && !StringUtils.isEmpty(level)) {
					loggers.add(new String[] { name, level });
				}
			}

			// 按包名排序
			Collections.sort(loggers, new Comparator<String[]>() {
				@Override
				public int compare(String[] o1, String[] o2) {
					return o1[0].compareTo(o2[0]);
				}
			});

			logLevels = Lists.newArrayList("DEBUG", "INFO", "ERROR");
		}

		return SUCCESS;
	}
}
